# -*- coding: utf-8 -*-
class SalesStrategyController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:newSalesStrategy,:editSalesStrategy,:salesStrategyLock]

  def salesStrategyList

  end

  def create
    begin
      salesStrategy = SalesStrategy.new
      salesStrategy.department_id =  session[:department_id]
      salesStrategy.employee_id =  session[:employee_id]
      salesStrategy.company_id = params[:company_id]
      salesStrategy.name = params[:name]
      salesStrategy.discount = params[:discount]
      salesStrategy.description = params[:description]
      salesStrategy.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end

    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def update
    begin
      salesStrategy = SalesStrategy.find(params[:id])
      salesStrategy.employee_id =  session[:employee_id]
      salesStrategy.department_id =  session[:department_id]
      salesStrategy.company_id = params[:company_id]
      salesStrategy.name = params[:name]
      salesStrategy.discount = params[:discount]
      salesStrategy.description = params[:description]
      salesStrategy.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end

    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #锁定或解锁销售策略
  def salesStrategyLock
    salesStrategy = SalesStrategy.find(params[:id])
    if salesStrategy.is_locked == 1
      salesStrategy.is_locked = 0
    else
      salesStrategy.is_locked = 1
    end
    salesStrategy.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  def getAllSalesStrategies
    forCBB = params[:for_cbb]
    if forCBB == 'true'
      salesStrategies = SalesStrategy.where("is_locked = ? and company_id = ?",0,session[:company_id]).order("company_id")
    else
      salesStrategies = SalesStrategy.order("company_id")
    end
    
    jsonStr="{totalProperty:"+salesStrategies.length.to_s+",root:"+salesStrategies.to_json(:include=>{:company=>{:only=>[:id,:name]},:employee=>{:only=>[:id,:name]}})+"}"

    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getSalesStrategyById
    salesStrategy = SalesStrategy.find(params[:id])
    rootStr = salesStrategy.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
end
